package com.buba.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import result.CommonException;
import result.CommonResult;

import java.util.LinkedHashMap;
import java.util.Map;


/**
 * 捕获控制层异常
 *
 * @auther zcy
 * @data 2019/10/11 10:12
 */
public class BaseController {


    /**
     * 捕获异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(Exception ex) {
        Map<String, Object> responseData = new LinkedHashMap<>();
        if (ex instanceof CommonException) {
            CommonException commonException = (CommonException) ex;
            responseData.put("errMsg", commonException.getErrMsg());
            responseData.put("errCode", commonException.getErrCode());
        } else {
            responseData.put("errMsg", ex.toString());
            responseData.put("errCode", ex.getStackTrace());
        }
        return CommonResult.fail(responseData);
    }
}
